<?php

namespace app\modules\web\controllers\common;

use yii\web\Controller;
use \app\common\components\BaseWebController;
use \app\models\User;
use \app\common\services\UrlService;
use \app\common\services\applog\AppLogService;
class BaseController extends BaseWebController
{
	private $auth_token_name="cj";
    public $current_user=null;
	public $allowAllAction=[
		'web/user/login'
	];
    public function __construct($id,$modules,array $config=[])
    {
        parent::__construct($id,$modules,$config);
        $this->layout="main";
    }
    public function beforeAction( $action )
    {
    	//验证是否登录
    	if(in_array($action->getUniqueId(),$this->allowAllAction)){
    		return true;
    	}
    	$is_login=$this->checkLoginStatus();
        if(!$is_login){
        	
        	if(\Yii::$app->request->isAjax){
        		$this->renderJson([],"请登录",-302);
        	}else{
        		$this->redirect(UrlService::buildWebUrl('/user/login'));
        	}
        	return false;
        }
        AppLogService::addAppAccessLog($this->current_user['uid']);
        return true;
    }
    //返回是否登录成功
    public function checkLoginStatus(){
    	$auth_cookies=$this->getCookie($this->auth_token_name);
        if(!$auth_cookies){
        	return false;
        }
        list($auth_token,$uid)=explode("#", $auth_cookies);
        if(!$auth_token || !$uid){
        	return false;
        }
        if(!preg_match("/^\d+$/",$uid)){
        	return false;
        }
        $is_find=User::find()->where(["uid"=>$uid])->one();
        if(!$is_find){
        	return false;
        }
        if($auth_token!=$this->getAuthToken($is_find)){
            return false;
        }
        $this->current_user=$is_find;
        return true;
    }	
    //设置登录状态
    public function setLoginStatus($user_info){
        $auth_token=$this->getAuthToken($user_info);
        $this->setCookie($this->auth_token_name,$auth_token."#".$user_info['uid']);
    }

    //移除登录状态
    public function removeLogin(){
        $this->removeCookies($this->auth_token_name);
    }
    public function getAuthToken($user_info){
        return md5($user_info['login_name'].$user_info['login_pwd'].$user_info['login_salt']);
    }
}
